package com.example.recall_application.mvp.ui.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.blankj.utilcode.util.SPUtils;
import com.example.recall_application.R;
import com.example.recall_application.app.Constants;
import com.example.recall_application.di.component.DaggerConfigComponent;
import com.example.recall_application.mvp.contract.ConfigContract;
import com.example.recall_application.mvp.incomingcall.PhoneListener;
import com.example.recall_application.mvp.presenter.ConfigPresenter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/11/2019 21:41
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class ConfigActivity extends BaseActivity<ConfigPresenter> implements ConfigContract.View {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.swh_all)
    Switch swhAll;
    @BindView(R.id.tv_read_contacts)
    TextView tvReadContacts;
    @BindView(R.id.tv_change_contacts)
    TextView tvChangeContacts;
    @BindView(R.id.tv_read_calls)
    TextView tvReadCalls;
    @BindView(R.id.tv_change_calls)
    TextView tvChangeCalls;
    @BindView(R.id.tv_read_sms)
    TextView tvReadSms;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_audio)
    TextView tvAudio;
    @BindView(R.id.tv_storage)
    TextView tvStorage;
    @BindView(R.id.tv_auto_start)
    TextView tvAutoStart;
    @BindView(R.id.tv_shendian)
    TextView tvShendian;
    @BindView(R.id.swh_sip)
    Switch swhSip;
    @BindView(R.id.ll_quit)
    LinearLayout llQuit;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerConfigComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_config; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {


        functionInit(SPUtils.getInstance().getInt(Constants.Option));
        initListener();
    }

    public void functionInit(int option) {
        switch (option) {
            case 0:
                swhAll.setChecked(false);
                swhSip.setChecked(false);
                break;
            case 1:
                swhAll.setChecked(true);
                swhSip.setChecked(false);
                break;
            case 2:
                swhAll.setChecked(false);
                swhSip.setChecked(true);
                break;
            case 3:
                swhAll.setChecked(true);
                swhSip.setChecked(true);
                break;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onStart() {
        super.onStart();
        checkPermission();
        EventBus.getDefault().post(Constants.GET_CONTACTS);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void checkPermission() {
        //读取联系人权限
        if (this.checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            tvReadContacts.setText("去设置");
            tvReadContacts.setTextColor(Color.parseColor("#F8612C"));
        } else {
            tvReadContacts.setText("已授权");
            tvReadContacts.setTextColor(getColor(R.color.blue));
        }


        //修改联系人权限
        if (this.checkSelfPermission(Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            tvChangeContacts.setText("去设置");
            tvChangeContacts.setTextColor(Color.parseColor("#F8612C"));
        } else {
            tvChangeContacts.setText("已授权");
            tvChangeContacts.setTextColor(getColor(R.color.blue));
        }


        //读取通话记录权限
        if (this.checkSelfPermission(Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            tvReadCalls.setText("去设置");
            tvReadCalls.setTextColor(Color.parseColor("#F8612C"));
        } else {
            tvReadCalls.setText("已授权");
            tvReadCalls.setTextColor(getColor(R.color.blue));
        }


        //修改通话记录权限

        if (this.checkSelfPermission(Manifest.permission.WRITE_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
            tvChangeCalls.setText("去设置");
            tvChangeCalls.setTextColor(Color.parseColor("#F8612C"));
        } else {
            tvChangeCalls.setText("已授权");
            tvChangeCalls.setTextColor(getColor(R.color.blue));
        }


        //读取短信权限
        if (this.checkSelfPermission(Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
            tvReadSms.setText("去设置");
            tvReadSms.setTextColor(Color.parseColor("#F8612C"));
        } else {
            tvReadSms.setText("已授权");
            tvReadSms.setTextColor(getColor(R.color.blue));
        }


        //拨打、挂断电话权限
        if (this.checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            tvPhone.setText("去设置");
            tvPhone.setTextColor(Color.parseColor("#F8612C"));
        } else {
            tvPhone.setText("已授权");
            tvPhone.setTextColor(getColor(R.color.blue));
        }


        //录音权限权限
        if (this.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            tvAudio.setText("去设置");
            tvAudio.setTextColor(Color.parseColor("#F8612C"));
        } else {
            tvAudio.setText("已授权");
            tvAudio.setTextColor(getColor(R.color.blue));
        }

        //存储读写权限
        if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            tvStorage.setText("去设置");
            tvStorage.setTextColor(Color.parseColor("#F8612C"));
        } else {
            tvStorage.setText("已授权");
            tvStorage.setTextColor(getColor(R.color.blue));
        }
    }

    private void initListener() {

        swhAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                boolean flag = swhSip.isChecked();
                if (isChecked) {
                    if (flag) {
                        mPresenter.setConfigOption(3);
                    } else {
                        mPresenter.setConfigOption(1);
                    }
                    PhoneListener.flag_all = true;
                    EventBus.getDefault().post(Constants.GET_CONTACTS);
                } else {
                    if (flag) {
                        mPresenter.setConfigOption(2);
                    } else {
                        mPresenter.setConfigOption(0);
                    }
                    PhoneListener.flag_all = false;
                }

            }
        });

        swhSip.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                boolean flag = swhAll.isChecked();

                if (isChecked) {
                    if (flag) {
                        mPresenter.setConfigOption(3);
                    } else {
                        mPresenter.setConfigOption(2);
                    }
                    EventBus.getDefault().post(Constants.Flag);
                } else {
                    if (flag) {
                        mPresenter.setConfigOption(1);
                    } else {
                        mPresenter.setConfigOption(0);
                    }
                    EventBus.getDefault().post(Constants.Sip_unregister);
                }
               // mPresenter.setConfigOption(1);
            }
        });

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
       finish();
    }

    @Subscriber(mode = ThreadMode.MAIN)
    public void kill(String flag){
        if(flag.equals(Constants.KILL)){
            onDestroy();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.ll_quit,R.id.iv_back, R.id.tv_read_contacts, R.id.tv_change_contacts, R.id.tv_read_calls, R.id.tv_change_calls, R.id.tv_read_sms, R.id.tv_phone, R.id.tv_audio, R.id.tv_storage, R.id.tv_auto_start, R.id.tv_shendian})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_quit:

                new AlertDialog.Builder(this)
                        .setTitle("确认退出")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                SPUtils.getInstance().put(Constants.uuid, "");
                                Toast.makeText(ConfigActivity.this, "已清除本地uuid!", Toast.LENGTH_SHORT).show();
                                killMyself();
                            }
                        })
                        .show();


                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_read_contacts:

            case R.id.tv_change_contacts:

            case R.id.tv_read_calls:

            case R.id.tv_change_calls:

            case R.id.tv_read_sms:

            case R.id.tv_phone:

            case R.id.tv_audio:

            case R.id.tv_storage:

            case R.id.tv_auto_start:

            case R.id.tv_shendian:
                if (((TextView) view).getText().toString().equals("去设置")) {
                    goSetting();
                }
                break;
        }
    }

    public void goSetting() {
        if ("xiaomi".equalsIgnoreCase(Build.MANUFACTURER)) {
            Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);

        } else {
            Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }
    }

}
